﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace CompositionPlugin.Service
{
    public class ModuleLog : IModuleLog
    {
        internal ModuleLog(Log parentLog, TraceSource traceSource)
        {
            if (parentLog == null)
                throw new ArgumentNullException("parentLog");
            if (traceSource == null)
                throw new ArgumentNullException("traceSource");
            this.ParentLog = parentLog;
        }

        public virtual void Initialize() { }

        public void Write(TraceEventType eventType, int id, string message)
        {
            if (this._traceSource != null)
                this._traceSource.TraceEvent(eventType, id, message);
        }

        public void Initialize<T>(SystemRuntime.Module<T> module) where T : class
        {
            this.Write(TraceEventType.Information, Log.DefaultEventID, string.Format("Child log for {0} start running", module.Definition.Metadata.Name));
        }

        public void Destroy<T>(SystemRuntime.Module<T> module) where T : class
        {
            this.Write(TraceEventType.Information, Log.DefaultEventID, string.Format("Child log for {0} stop running", module.Definition.Metadata.Name));
            // detach this child log
            this.ParentLog.DetachChildLog(this);
            this._traceSource = null;
        }

        public virtual void OnRuntimeDisposing() { }

        #region internal
        /// <summary>
        /// Parent log
        /// </summary>
        internal Log ParentLog { get; set; }

        #endregion

        #region private

        private TraceSource _traceSource;

        #endregion
    }
}
